package edu.ubb.remeye.communication.message.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import edu.ubb.remeye.communication.message.Message;

/**
 * Message encoder class.
 * 
 * @author Andrew Ianicicau
 *
 */
public class MessageEncoder implements ProtocolEncoder {

	///////////////////////////////////////////////////////////////////////////////////
	////		ATTRIBUTES - MessageEncoder
	///////////////////////////////////////////////////////////////////////////////////

	/**
	 * Number of bytes for header information.
	 */
	private static final int headerBytesNumber = 5; 

	
	
	///////////////////////////////////////////////////////////////////////////////////
	////		METHODS - MessageEncoder
	///////////////////////////////////////////////////////////////////////////////////
	
	@Override
	public void dispose(IoSession session) throws Exception {
		// nothing to dispose
	}

	/**
	 * Deconstructing the message into a byte array.
	 */
	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		Message msg = (Message) message;
		IoBuffer buffer = IoBuffer.allocate(msg.getMessage().length + headerBytesNumber, false);
		buffer.putInt(msg.getMessage().length + 1);
		buffer.put((byte) msg.getMessageType().ordinal());
		buffer.put(msg.getMessage());
		buffer.flip();
		
		out.write(buffer);
		out.flush();
	}

}
